import React, { Component } from 'react'
import { Redirect, Route, Switch, withRouter } from 'react-router-dom'

class Router extends Component{
    constructor() {
        super()
        this.state = {
            route: [
                {
                    path: '/login',
                    component: React.lazy(() => import('../pages/Login')),
                    meta: '登录',
                    isExact: true,
                    needLogin:false,
                },
                {
                    path: '/register',
                    component: React.lazy(() => import('../pages/Register')),
                    meta: '注册',
                    isExact: true,
                    needLogin:false,
                },
                {
                    path: '/',
                    component: React.lazy(() => import('../pages/Index')),
                    meta: '首页',
                    isExact: false,
                    needLogin:false,
                },
                {
                    to: '/',
                }
            ]
        }
    }
    render() {
        let {route} = this.state
        return (
            <React.Fragment>
                <React.Suspense fallback={<mark>loading....</mark>}>
                    <Switch>
                        {/* <Route path="/login" exact component={}></Route>
                        <Route path="/" component={}></Route>
                        <Redirect to="/"></Redirect> */}
                        {
                            route.map(item =>
                                item.path ? <Route path={item.path} key={item.path} exact={item.isExact} render={() => {
                                    if (item.meta) {
                                        document.title = item.meta || '小U优选'
                                    }
                                    if (item.needLogin) {
                                        // let isLogin = true;
                                        if (!localStorage.getItem('user')) {
                                            return <Redirect to="/login"></Redirect>
                                        }
                                    }
                                    let Component = withRouter(item.component);
                                    return <Component></Component>
                                }}></Route> : <Redirect to={item.to}></Redirect>
                            )
                        }
                    </Switch>
                </React.Suspense>
            </React.Fragment>
        )
    }
}
export default Router